package itsm.isperp.framework.data.excel.executor;

import itsm.isperp.framework.data.excel.ExcelData;
import itsm.isperp.framework.data.excel.ImportCellDesc;
import itsm.isperp.framework.data.excel.validate.AbstractValidator;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * 处理Excel数据校验
 */
public class ValidateUtil {

	/**
	 * 处理单元格的数据校验工作
	 */
	public static void validateCell(ExcelData excelData, ImportCellDesc cellDesc) {
		// 如果没有设置校验器
		if (excelData == null || cellDesc == null
				|| cellDesc.getValidatorList() == null
				|| cellDesc.getValidatorList().size() <= 0) {
			return;
		}
		List<String> validators = cellDesc.getValidatorList();
		for (String validator : validators) {
			try {
				Class<?> clazz = Class.forName(validator);

				Object obj = clazz.newInstance();
				if (obj == null) {
					continue;
				}
				if (!(obj instanceof AbstractValidator)) {
					excelData.addErrorMsg(cellDesc.getCellRef(),
							"请检查, 数据校验器必须继承AbstractValidator : " + validator);
					continue;
				}
				AbstractValidator validatorInstance = (AbstractValidator) obj;
				// 设置单元格的值、位置
				validatorInstance.setCellRef(cellDesc.getCellRef());
				validatorInstance.setFieldValue(cellDesc.getFieldValue());
				validatorInstance.setCell(cellDesc);
				validatorInstance.setRepeatCellList(excelData
						.getRepeatCellList());
				validatorInstance.setAllCellList(excelData.getAllCellList());
				// 执行校验
				String errorMsg = validatorInstance.processValidate(cellDesc
						.getParams());
				// 如果校验
				if (StringUtils.isNotEmpty(errorMsg)
						|| !AbstractValidator.OK.equals(errorMsg)) {
					excelData.addErrorMsg(cellDesc.getCellRef(), errorMsg);
				}
			} catch (ClassNotFoundException e) {
				excelData.addErrorMsg(AbstractValidator.SYSTEM_ERROR,
						"请检查, 不存在的数据校验器 : " + validator);
				// e.printStackTrace();
			} catch (InstantiationException e) {
				excelData.addErrorMsg(AbstractValidator.SYSTEM_ERROR, "请检查, "
						+ validator + ", 必须要有空构造函数!");
				// e.printStackTrace();
			} catch (IllegalAccessException e) {
				excelData.addErrorMsg(AbstractValidator.SYSTEM_ERROR, "请检查, "
						+ validator + ", 构造函数必须为public!");
				// e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}